﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.XWPF.UserModel;

namespace Utils.Npoi
{
    public class NpoiWord
    {
        private readonly XWPFDocument _DOC;

        public NpoiWord()
        {
            _DOC = new XWPFDocument();
        }

        public void CreateBookmark(string bookmark)
        {
            int m_bookId = Guid.NewGuid().GetHashCode();//同一段内有多个书签，需要不同的Id，不同段的书签Id可以相同
            CT_P mp = _DOC.Document.body.AddNewP();
            mp.AddNewPPr().AddNewJc().val = ST_Jc.both;
            mp.AddNewPPr().AddNewSpacing().line = "400";//固定行距20磅

            mp.AddNewPPr().AddNewSpacing().lineRule = ST_LineSpacingRule.exact;

            mp.Items = new System.Collections.ArrayList();

            CT_Bookmark m_ctbook1 = new CT_Bookmark();

            m_bookId = mp.Items.Count;

            m_ctbook1.id = m_bookId.ToString(); //"0";

            m_ctbook1.name = bookmark;//书签名，超链接用

            mp.Items.Add(m_ctbook1);

            mp.ItemsElementName = new List<ParagraphItemsChoiceType>();

            mp.ItemsElementName.Add(ParagraphItemsChoiceType.bookmarkStart);

            mp.AddNewR().AddNewT().Value = bookmark + "-------------------.";

            //书签0结束

            m_ctbook1 = new CT_Bookmark
            {
                id = m_bookId.ToString()//"0";
            };

            mp.Items.Add(m_ctbook1);

            mp.ItemsElementName.Add(ParagraphItemsChoiceType.bookmarkEnd);
        }

        public void SaveToWord(string newPath)
        {
            using (FileStream fs = new FileStream(newPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                _DOC.Write(fs);
            }
        }

    }
}
